﻿using Basic.HrGatewayModular.Interface;
using Basic.HrGatewayModular.Model.LoginUser;
using Basic.HrRemoteModel.LoginUser.Model;
using Lazy.Captcha.Core.Interface;
using WeDonekRpc.Helper;
using WeDonekRpc.HttpApiGateway.Interface;
using WeDonekRpc.HttpApiGateway.Response;

namespace Basic.HrGatewayModular.Extend
{
    internal class PwdResetService : IPwdResetService
    {
        private readonly ILoginUserService _Service;

        private readonly IIpLimitService _IpLimit;

        private readonly IPwdResetVerCode _VerCode;
        private static readonly string _IpLimitKey = "PwdReset";

        public PwdResetService ( ILoginUserService service,
            IIpLimitService ipLimit,
            IPwdResetVerCode verCode )
        {
            this._Service = service;
            this._IpLimit = ipLimit;
            this._VerCode = verCode;
        }
        public IResponse CreateCode ( string loginName )
        {
            byte[] img = this._VerCode.Generate(loginName);
            return new StreamResponse(img, "verCode.png");
        }
        public void ResetUserPwd ( UIResetPwdArg obj, string ip )
        {
            this._IpLimit.CheckIsLimit(_IpLimitKey, ip);
            this._VerCode.Validate(obj.LoginName, obj.VerCode);
            try
            {
                this._Service.ResetPwd(new ResetPwdArg
                {
                    LoginName = obj.LoginName,
                    NewPwd = obj.NewPwd,
                    Password = obj.Password,
                });
            }
            catch ( ErrorException e )
            {
                if ( this._IpLimit.IsLimit(e) )
                {
                    this._IpLimit.LimitTally(_IpLimitKey, ip);
                }
                throw;
            }
        }
    }
}
